package org.jmc.refmanager.web.wicket.provider;

import java.util.Iterator;

import org.apache.wicket.extensions.markup.html.repeater.util.SortParam;
import org.apache.wicket.extensions.markup.html.repeater.util.SortableDataProvider;
import org.apache.wicket.injection.web.InjectorHolder;
import org.apache.wicket.model.IModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.jmc.refmanager.domain.dao.QueryParam;
import org.jmc.refmanager.domain.model.Change;
import org.jmc.refmanager.domain.service.ChangeManager;
import org.jmc.refmanager.web.wicket.model.ChangeModel;

public class MyTasksSortableDataProvider extends SortableDataProvider<Change> {
	private static final long serialVersionUID = 1L;
	
	@SpringBean(name="taskManager")
	private ChangeManager taskManager;
	
	private QueryParam<Change> queryParameters;
	
	/**
	 * 
	 */
	public MyTasksSortableDataProvider(QueryParam<Change> params) {
		super();
		InjectorHolder.getInjector().inject(this);
		this.queryParameters = params;
	}

	@Override
	public Iterator<? extends Change> iterator(int first, int count) {
		SortParam sortParam = getSort();
		if (this.queryParameters == null) {
			this.queryParameters = new QueryParam<Change>();
		}
		
		if (sortParam != null) {
			this.queryParameters.setSortAsc(sortParam.isAscending());
			this.queryParameters.setSortPropertyName(sortParam.getProperty());
		}
		
		this.queryParameters.setFirst(first);
		this.queryParameters.setCount(count);

		// Appel e la couche de service
		return taskManager.findMyTasks(queryParameters).iterator();
	}

	@Override
	public IModel<Change> model(Change change) {
		return new ChangeModel(change);
	}

	@Override
	public int size() {
		// Appel e la couche de service
		return taskManager.countMyTasks(queryParameters);
	}
}
